package com.moleq.dialog;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.moleq.adapter.NetworkReportListAdapter;
import com.moleq.adapter.TextAndCheckboxListAdapter;
import com.moleq.base.MoleQBaseDialog;
import com.moleq.base.OnResultListener;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.mgpos.activities.NetworkSettingActivity;
import com.moleq.mgpos.activities.R;
import com.moleq.models.TextAndCheckBox;
import com.moleq.network.CommunicationCallback;
import com.moleq.network.ConnectHandler;

public class NetworkStationDialog extends MoleQBaseDialog {

	
	public static final int BUSY = 1;
	public static final int FREE = 0;
	public static final int REPORT_READY = 2;
	
	private OnResultListener mOnResultListener;
	private Button mButtonBack,mButtonOk,btn_report;
	private Context mContext;
	private ListView lv_station;
	private TextView tv_title;
	private ImageView iv_netrefresh;
	private NetworkReportListAdapter mNetworkReportListAdapter;

	private String mloaclIpAddress = "";
	private List<TextAndCheckBox> listItem;
	private ConnectHandler mNetworkMonitor = null;
	
	
	private CommunicationCallback mCmmCallback = new CommunicationCallback() {

		@Override
		public void onError(String errMsg) {
			// TODO Auto-generated method stub
			Log.e("networksetting", " error message -> " + errMsg);
			// handler.sendMessage(handler.obtainMessage(0, ""));
		}

		@Override
		public void onConnected(String ip) {

			Log.i("networksetting", ip + " is connected...");
			setOnlineIpAddress(ip);

		}

		@Override
		public void onCheckNetworkStart() {
			mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(1, ""));
		}

		@Override
		public void onCheckNetworkComplete() {
			mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(0, ""));

			mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(3, ""));

		}

		@Override
		public void onDisconnected(String ip) {
			Log.i("networksetting", ip + " is disconnected...");

		}
	};

	private void setOnlineIpAddress(String ip) {
		if (listItem != null && listItem.size() > 0) {

			for (int i = 0; i < listItem.size(); i++) {
				if (ip.endsWith(listItem.get(i).getIp())) {
					listItem.get(i).setOnline(true);
					Log.i("networksetting", " check ip -> " + listItem.get(i).getIp());
					break;
				}
			}

		}
	}
	
	private void resetIpAddres(){
		if (listItem != null && listItem.size() > 0) {

			for (int i = 0; i < listItem.size(); i++) {
				listItem.get(i).setOnline(false);
			}
			mNetworkReportListAdapter.notifyDataSetChanged();
		}
	}
	
	private ProgressDialog mProcessingDlg;
	private Handler mNetworkhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				Log.i("networksetting", " dismiss processing dialog -> ");
				if (mProcessingDlg != null || mProcessingDlg.isShowing()) {
					mProcessingDlg.dismiss();
				}
				break;
			case 1:
				Log.i("networksetting", " open processing dialog -> ");
				mProcessingDlg = new ProgressDialog(mContext);
				mProcessingDlg.setTitle("");
				mProcessingDlg.setMessage("Scanning terminal, Please wait..");
				mProcessingDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				mProcessingDlg.getWindow().setWindowAnimations(android.R.style.Animation);
				mProcessingDlg.show();
				break;
			case 3:
				mNetworkReportListAdapter.notifyDataSetChanged();
				break;

			default:
				break;
			}
		}
	};
	
	public String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("WifiPreference IpAddress", ex.toString());
		}
		return null;
	}
	
	private Button.OnClickListener mOnClickListener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {	
			switch(v.getId()){
			case R.id.btn_cancel:
//				dismiss();
				MessageBox.show(mContext, "Do you want to terminate this action?",onClickMessageListener,MessageDialog.MESSAGE_BOX_YES_NO);
				break;
			case R.id.btn_ok:	
				onReturnValue(R.id.btn_ok, mNetworkReportListAdapter);
				break;
			case R.id.btn_report:
				onReturnValue(R.id.btn_report, "");
				break;
			case R.id.iv_netrefresh:
				resetIpAddres();
				
				new Thread() {
					public void run() {
						mNetworkMonitor.checkIpAddress(getIpList());
					};
				}.start();
				mNetworkReportListAdapter.notifyDataSetChanged();
				break;
			}
		}
	};
	
	public OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {
		
		public void onClickYes() {
			dismiss();
		}
		
		public void onClickOK() {
		}
		
		public void onClickNo() {
		}
	};
		
	public void onCloseWithReturn(Object obj){
		mOnResultListener.onReturnValue(0,obj);
		dismiss();
	}
	
	public NetworkStationDialog(Context context, Object base, List<TextAndCheckBox> listItem) {
		super(context,base);
		mContext = context;
		this.listItem = listItem;
	}
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// set UI layout
		this.setContentView(R.layout.dialog_perview_network_rpt);
		this.setCancelable(false);
	
		mButtonBack = (Button) findViewById(R.id.btn_cancel);
		mButtonBack.setOnClickListener(mOnClickListener);
		
		mButtonOk = (Button) findViewById(R.id.btn_ok);
		mButtonOk.setOnClickListener(mOnClickListener);
		
		btn_report = (Button) findViewById(R.id.btn_report);
		btn_report.setOnClickListener(mOnClickListener);

		lv_station = (ListView) findViewById(R.id.lv_station);
		tv_title = (TextView) findViewById(R.id.tv_title);
		iv_netrefresh = (ImageView) findViewById(R.id.iv_netrefresh);
		iv_netrefresh.setOnClickListener(mOnClickListener);
		mloaclIpAddress = getLocalIpAddress();
		if (listItem != null && listItem.size() > 0) {
			for (int i = 0; i < listItem.size(); i++) {
				if(listItem.get(i).getIp().equals(mloaclIpAddress)){
					listItem.get(i).setLocal(true);
					listItem.get(i).setOnline(true);
				}
			}
		}
		mNetworkMonitor = new ConnectHandler(6677, mCmmCallback);
	}
	
	public void show(){
		super.show();	
		mNetworkReportListAdapter = new NetworkReportListAdapter(mContext, listItem);
		lv_station.setAdapter(mNetworkReportListAdapter);
		tv_title.setText("Ready");
		resetIpAddres();
		
		new Thread() {
			public void run() {
				mNetworkMonitor.checkIpAddress(getIpList());
			};
		}.start();
		mNetworkReportListAdapter.notifyDataSetChanged();
	}
	
	public List<String> getIpList() {
		List<String> ips = new ArrayList<String>();
		if (listItem != null && listItem.size() > 0) {
			for (int i = 0; i < listItem.size(); i++) {
				String ipAddress = listItem.get(i).getIp();
				if (!ipAddress.equals(mloaclIpAddress)) {
					ips.add(ipAddress);
				}
			}
		}
		return ips;
	}
	
	public void setState(int state){
		mNetworkReportListAdapter.setState(state);
		switch (state) {
		case NetworkStationDialog.BUSY:
			btn_report.setVisibility(View.INVISIBLE);
			mButtonOk.setVisibility(View.INVISIBLE);
			tv_title.setText("Retrieving...");
			
			break;
		case NetworkStationDialog.FREE:
			mButtonOk.setVisibility(View.VISIBLE);
			btn_report.setVisibility(View.INVISIBLE);
			break;
		case NetworkStationDialog.REPORT_READY:
			tv_title.setText("Finished");
			mButtonOk.setVisibility(View.INVISIBLE);
			btn_report.setVisibility(View.VISIBLE);
			refresh();
			break;
		default:
			break;
		}
	}
	
	public void refresh(){
		mNetworkReportListAdapter.notifyDataSetChanged();
	}
}
